/*
	* --------------------------------------------------------------------------
	*
  * Copyright 2011 Matthew West T/A Developer City
	*
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
	*
  *   http://www.apache.org/licenses/LICENSE-2.0
	*
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  *
  * --------------------------------------------------------------------------
*/
$(function() {
	
	graphArray = [];
	graphArrayLegacy = [];
	graphKey = [];
	currentProcessed = 0;
	totalDaysUse = 0;

	thirtyDaysAgo = minusThirtyDays();
	dayInMilliseconds = 1000*60*60*24;

	for (var i = 0; i <= 30; i++) {
		startTime = thirtyDaysAgo + (i * dayInMilliseconds);
		endTime = startTime + (dayInMilliseconds - 1);
		var cD = new Date();
		cD.setTime(startTime);
		var day = cD.getDate();
	
		getVisitsOnDay(startTime, endTime, graphArray);
	
		graphKey.push([i, day]);
	}
	
	for (var i = 0; i <= 30; i++) {
		startTime = (thirtyDaysAgo * 2) + (i * dayInMilliseconds);
		endTime = startTime + (dayInMilliseconds - 1);
		var cD = new Date();
		cD.setTime(startTime);
		var day = cD.getDate();
	
		getVisitsOnDay(startTime, endTime, graphArrayLegacy);
	}
	
});


function getVisitsOnDay(startTime, endTime, array) {
	chrome.history.search({
		      'text': '',
		      'startTime': startTime,
		      'endTime': endTime,
		      'maxResults': 1000000000
	},
	function(historyItems) {
		var start = new Date();
		start.setTime(startTime);
		
		var end = new Date();
		end.setTime(endTime);
		
		totalVisits = historyItems.length;
		
		array.push([currentProcessed, totalVisits]);
		
		currentProcessed++;
		
		if (currentProcessed == 31) {
      // Reset the current item
      currentProcessed = 0;
      
		}
	});
}


/*
*	Get the date 30 days ago
*/
function minusThirtyDays() {
	// Calculate the start date
	// 30 Days before the current date
	var milliMonth = 1000*60*60*24*30; // Calculate how many milliseconds are in 30 days
	var d = new Date();
	var current = d.getTime(); // Set d to the current time
	var offsetDate = current - milliMonth; // Calculate the date/time 30 days ago
	d.setTime(offsetDate); // Reset the date object to the offsetTime
	d.setMinutes(0); // Reset the minutes to 0
	d.setHours(0); // Reset the hours to 0
	d.setSeconds(0); // Reset the seconds to 0
	d.setMilliseconds(0); // Reset the milliseconds to 0
	
	thirtyDaysAgo = d.getTime(); // Set the start time variable to d in milliseconds since epoch
	
	return thirtyDaysAgo;
}
